//
//  MTWithdrawTaskListController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/7.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa
import Moya
import Result

class MTWithdrawTaskListController: BaseViewController {
    /// MineApi
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    private let disposeBag = DisposeBag()
    
    var rate: Int = 0 {
        didSet {
            rateLab.text = "\(rate)%"
        }
    }
    
    private var result: [MTWithdrawReportSubModel] = []
    
    lazy var rateLab: UILabel = {
        let perlabel = UILabel()
        perlabel.textColor = UIColor(hex:0xffc000)
        perlabel.font = PingFangSCSemiboldFont(28)
        return perlabel
    }()
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(WithdrawTaskCell.self, forCellReuseIdentifier: WithdrawTaskCell.reuseIdentity())
        table.separatorInset = UIEdgeInsets.zero
        table.tableFooterView = UIView()
        table.estimatedRowHeight = 44//预估高度，随便设置
        table.rowHeight = UITableView.automaticDimension
        table.backgroundColor = UIColor.theme.background
        table.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadData()

        }
        return table
    }()
    
    private func loadData() {
        provider.rx.requestResult(.withdrawRule).subscribe(onNext: { [weak self] (result: Result<MTWithdrawReportModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if response.code == 200, let model = response.result {
                    //                    weakself.presentWithdrawAlert(with: "提现", message: "您的\(model.ticketAmount)点券将提现成\n\(model.rmbAmount)人民币，是否提现？") {
                    //                        weakself.applyWithdraw(with: model)
                    //                    }
                    weakself.result = model
                    weakself.tableView.reloadData()
                } else {
                    AlertManager.presentAlertView(message: response.message ?? "申请失败")
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: disposeBag)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "我的提现比例"
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 56, height: 20))
        button.setTitle("联系客服", for: .normal)
        button.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        button.titleLabel?.font = PingFangSCMediumFont(14)
        button.addTarget(self, action: #selector(withdrawTaskListViewController(didClickContactButton:)), for: .touchUpInside)
        let rightBarButton = UIBarButtonItem(customView: button)
        self.navigationItem.rightBarButtonItem = rightBarButton
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        loadData()
    }
}

extension MTWithdrawTaskListController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTWithdrawTaskListController {
    
    private func withdrawTaskListViewController(didClickContactButton sender: UIButton) {
        if let un = UserCenter.default.customerUserName {
            JMSGConversation.createSingleConversation(withUsername: un) { [weak self] (conversation, error) in
                guard let weakSelf = self else { return }
                if error == nil, conversation != nil {
                    if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[1] as? BaseNavController {
                        nav.selectCategory()
                        
                        DispatchQueue.main.after(0.25) {
                            let conv: JMSGConversation = conversation as! JMSGConversation
                            nav.pushViewController(JCChatViewController(conversation: conv), animated: true)
                        }
                        
                        DispatchQueue.main.after(1, execute: {
                            weakSelf.navigationController?.popToRootViewController(animated: false)
                        })
                    }
                }
            }
        }
    }
    
    
}

extension MTWithdrawTaskListController: UITableViewDataSource, UITableViewDelegate {
    
    //MARK: UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: WithdrawTaskCell.reuseIdentity(), for: indexPath) as! WithdrawTaskCell
        if result.count > indexPath.row {
            cell.model = result[indexPath.row]
            cell.delegate = self
        }
        return cell
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 90
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0x2f2f2f)
        view.addSubview(rateLab)
        let imageView = UIImageView()
        imageView.image = UIImage(named: "up")
        imageView.contentMode = .scaleAspectFill
        view.addSubview(imageView)
        let desclabel = UILabel()
        desclabel.text = "成长中"
        desclabel.textColor = .white
        desclabel.font = PingFangSCMediumFont(10)
        view.addSubview(desclabel)
        
        rateLab.snp.makeConstraints { (make) in
            make.centerY.centerX.equalTo(view)
        }
        
        imageView.snp.makeConstraints { (make) in
            make.top.equalTo(rateLab.snp.top).offset(8)
            make.left.equalTo(rateLab.snp.right).offset(2)
            make.width.equalTo(12)
            make.height.equalTo(14)
        }
        desclabel.snp.makeConstraints { (make) in
            make.top.equalTo(imageView)
            make.left.equalTo(imageView.snp.right).offset(2)
            make.width.equalTo(120)
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

extension MTWithdrawTaskListController: WithdrawTaskCellDelegate{
    func shareClick() {
        let xibView = InviteShareAlertView.init(frame: CGRect(x:0, y:0, width:ScreenWidth, height:ScreenHeight))
//        xibView.model = model
        UIApplication.mt_keyWindow?.addSubview(xibView)
    }
}
